﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TomNet.IMSC.Core.Contracts.Decoration;
using TomNet.IMSC.Model.DbModels.Decoration;
using TomNet.Web.Mvc.UI;
using TomNet.Web.Mvc;
using System.ComponentModel;
using TomNet.Web.Mvc.Security;
using TomNet.IMSC.Web.Areas.Decoration.Models;
using TomNet.IMSC.Core.Contracts.Organization;
using TomNet.IMSC.Core.Contracts.Common;
using TomNet.IMSC.Web.Filters;
using TomNet.IMSC.Model.DbModels.NewHouse;
using TomNet.IMSC.Core.Contracts.NewHouse;

namespace TomNet.IMSC.Web.Areas.Decoration.Controllers
{

    [Description("装修-装修公司管理")]
    [GlobalAuthorization]
    public class DecorationCompanyController : BaseController
    {
        public IDecorationCompanyContract DecorationCompanyContract { get; set; }
        public IStaffContract StaffContract { get; set; }
        public IImagesContract ImagesContract { get; set; }//图片 
        //public IBuildingTopContract BuildingTopContract { get; set; }
        // GET: Decoration/DecorationCompany
        #region 装修-装修公司列表
        [Description("装修-装修公司列表")]
        public ActionResult Index()
        {
            return View();
        }
        [Description("装修-装修公司列表")]
        public ActionResult GetList(int pageIndex, int pageSize, string search = "")
        {
            var query = (from q in DecorationCompanyContract.Entities
                         select new DecorationCompanyNew
                         {
                             Id = q.Id,
                             Name = q.Name,
                             Brokerage = q.Brokerage,
                             BandSawBrokerage = q.BandSawBrokerage,
                             AwardDescription = q.AwardDescription,
                             CommissionAccount = q.CommissionAccount,
                             DecorationCompanyInfo = q.DecorationCompanyInfo,
                             StarTarget = q.StarTarget,
                             StarTargetRemark = q.StarTargetRemark,
                             ShowIndex = q.ShowIndex,
                             Remark = q.Remark,
                             AgentID = q.AgentID,
                             MediumOfCommunicationStaffName = (from s in StaffContract.Entities where s.Id==q.MediumOfCommunicationStaffID select s.Name).FirstOrDefault(),
                             FeeScale = q.FeeScale,
                             Preferential = q.Preferential,
                             State = q.State,
                             FilingRules = q.FilingRules,
                             BandSawRules = q.BandSawRules,
                             TransactionRules = q.TransactionRules,
                             ImageCount= (from m in ImagesContract.Entities where m.GroupID == 6 && m.InterfixID == q.Id  && !m.IsDeleted select m).Count(),


                             //BeginTime = (from btc in BuildingTopContract.Entities where btc.UnionModule == 3 && q.Id == btc.UnionID select btc.BeginTime).FirstOrDefault(),
                             //EndTime = (from btc in BuildingTopContract.Entities where btc.UnionModule == 3 && !btc.IsDeleted && btc.BeginTime < DateTime.Now && btc.EndTime > DateTime.Now && q.Id == btc.UnionID select btc.EndTime).FirstOrDefault(),
                             //ShowIndex = (from btc in BuildingTopContract.Entities where btc.UnionModule == 3 && !btc.IsDeleted && btc.BeginTime < DateTime.Now && btc.EndTime > DateTime.Now && q.Id == btc.UnionID select btc.ShowIndex).FirstOrDefault(),
                             //CreatedTime = (from btc in BuildingTopContract.Entities where btc.UnionModule == 3 && !btc.IsDeleted && btc.BeginTime < DateTime.Now && btc.EndTime > DateTime.Now && q.Id == btc.UnionID select btc.CreatedTime).FirstOrDefault(),
                         });

            if (!string.IsNullOrWhiteSpace(search))
            { 
                query = query.Where(m => m.Name.Contains(search));
            }
            //数据总数
            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderBy(m => m.Id);

            ////默认给一个排序的字段 
            //var topCount = BuildingTopContract.Entities.Where(m => m.UnionModule == 4).Count();
            //if (topCount > 0)
            //{
            //    data = data.OrderByDescending(m => m.ShowIndex).ThenByDescending(m => m.BeginTime).ThenByDescending(m => m.Id);
            //}
            //else
            //{
            //    data = data.OrderByDescending(m => m.Id);

            //}

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : Enumerable.Empty<DecorationCompanyNew>().AsQueryable();

            //此处可以采用匿名对象 GridData<object>
            GridData<DecorationCompanyNew> gridData = new GridData<DecorationCompanyNew>() { Total = total, Rows = query.ToList() };

            //此处采用重写后的jsonResult
            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }
        #endregion

        #region 装修-添加装修公司
        [Description("装修-添加装修公司")]
        public ActionResult Insert()
        {
            return View();
        }
        [Description("装修-添加装修公司")]
        [HttpPost, AjaxOnly]
        public ActionResult InsertAsync(DecorationCompany entity)
        {
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);

            entity.StarTarget = "0";
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            try
            {
                entity.AgentID = model.AgentId;
                var query = DecorationCompanyContract.CheckExists(d => d.Name.Equals(entity.Name));
                if (query)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "已经存在相同的装修公司名称";
                }
                else
                {
                    var count = DecorationCompanyContract.Insert(entity);
                    if (count > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "录入成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "录入失败";
                    }
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 装修-修改装修公司
        [Description("装修-修改装修公司")]
        public ActionResult Edit(int id)
        {
            var entity = DecorationCompanyContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");
            ViewData["entity"] = entity;
            return View();
        }
        [Description("装修-修改装修公司")]
        [HttpPost, AjaxOnly]
        public ActionResult EditAsync(DecorationCompany entity)
        {
            var mm = DecorationCompanyContract.GetByKey(entity.Id);

            var result = new AjaxResult();
            try
            {
                var query = DecorationCompanyContract.CheckExists(d => d.Name.Equals(entity.Name) && d.Id != entity.Id);
                if (query)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "已经存在相同的装修公司";
                }
                else
                {
                    var count = DecorationCompanyContract.Update(entity);
                    if (count > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "修改成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "修改失败";
                    }
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 装修-删除装修公司
        [Description("装修-删除装修公司")]
        [HttpPost, AjaxOnly]
        public ActionResult DeleteAsync(string ids)
        {
            var result = new AjaxResult();
            try
            {
                string[] idsStr = ids.Split(new char[] { ',' });
                int[] idsInt = Array.ConvertAll(idsStr, id => Convert.ToInt32(id));
                DecorationCompanyContract.Delete(d => idsInt.Contains(d.Id));
                //DecorationCompanyContract.UpdateDirect(m => idsInt.Contains(m.Id));

                result.Type = AjaxResultType.Success;
                result.Content = "删除成功";
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 星标
        [Description("装修-查询星标")]
        public ActionResult SetStarTarget(int id = 0)
        {
            if (id == 0) throw new Exception("参数错误");
            var entity = DecorationCompanyContract.GetByKey(id);
            if (entity == null) throw new Exception("未找到该记录");
            ViewBag.entity = entity;
            return View();
        }
        /// <summary>
        /// 设置星标
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [Description("设置星标")]
        [AjaxOnly]
        public ActionResult EditSetStarTarget(DecorationCompany entity)
        {
            var result = new AjaxResult();
            try
            {
                var count = DecorationCompanyContract.UpdateDirect(d => entity.Id == d.Id,
                    d => new DecorationCompany { StarTarget = entity.StarTarget, StarTargetRemark = entity.StarTargetRemark });
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "修改成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "修改失败";
                }

            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }

            return JsonEx(result);
        }
        #endregion


        //#region 置顶
        //[Description("楼盘-置顶")]
        //public ActionResult EditTopData(int UnionModule, int UnionID, int BuildingTopID)
        //{
        //    ViewBag.UnionModule = UnionModule;
        //    ViewBag.UnionID = UnionID;
        //    if (BuildingTopID != 0)
        //    {
        //        var topEntity = BuildingTopContract.GetByKey(BuildingTopID);
        //        ViewBag.topEntity = topEntity;
        //    }
        //    else
        //    {
        //        var bt = new BuildingTop();
        //        bt.Id = 0;
        //        bt.UserID = 0;
        //        bt.UnionID = UnionID;
        //        bt.UnionModule = UnionModule;
        //        bt.BeginTime = DateTime.Now;
        //        bt.EndTime = DateTime.Now;
        //        bt.TopType = 0;
        //        bt.ShowIndex = 1;
        //        ViewBag.topEntity = bt;
        //    }
        //    return View();
        //}
        //[HttpPost]
        //public ActionResult EditTopDataAsync(BuildingTop entity)
        //{
        //    var result = new AjaxResult();
        //    var cookies = Common.CookiesManagement.GetCookies();
        //    var ticket = Common.CookiesManagement.GetTicket(cookies);
        //    var model = Common.CookiesManagement.GetLoginModel(ticket);
        //    if (entity.Id == 0)
        //    {
        //        entity.UserID = model.Id;
        //        //新增
        //        var count = BuildingTopContract.Insert(entity);
        //        if (count > 0)
        //        {
        //            result.Type = AjaxResultType.Success;
        //            result.Content = "修改成功";
        //        }
        //        else
        //        {
        //            result.Type = AjaxResultType.Error;
        //            result.Content = "修改失败";
        //        }
        //    }
        //    else
        //    {
        //        var BuildingTopModel = BuildingTopContract.GetByKey(entity.Id);
        //        BuildingTopModel.UserID = model.Id;
        //        BuildingTopModel.BeginTime = entity.BeginTime;
        //        BuildingTopModel.EndTime = entity.EndTime;
        //        BuildingTopModel.TopType = entity.TopType;
        //        BuildingTopModel.ShowIndex = entity.ShowIndex;
        //        var count = BuildingTopContract.Update(BuildingTopModel);
        //        if (count > 0)
        //        {
        //            result.Type = AjaxResultType.Success;
        //            result.Content = "修改成功";
        //        }
        //        else
        //        {
        //            result.Type = AjaxResultType.Error;
        //            result.Content = "修改失败";
        //        }
        //    }

        //    return JsonEx(result);
        //}
        //#endregion
    }
}